<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useMainStore } from "@/stores";
import { storeToRefs } from "pinia";
import { defaultImg } from "@/utils/constant";
import { PRODUCT_POOL } from "@/utils/constant/tableColumns";
import ProductInfo from "@/components/product-info.vue";
import ProductDetail from "@/components/product-detail.vue";
import api from "@/api";
import _ from "lodash";
import { message } from 'ant-design-vue';

const stores = useMainStore();
const { category_list } = storeToRefs(stores);
const openTemplate = ref(false);
const openPdDetail = ref(false);
const pdId = ref(null); // 商品详情id
const tabLoading = ref(false)

const templateList = ref([
  {
    label: "模板1",
    value: 1,
  },
  {
    label: "模板2",
    value: 2,
  },
]);
const selectTemplate = ref(templateList.value[0].value);
const pool_list = ref([]);

const sendtypes = ref([
  {
    name: "全部",
    id: '0',
  },
  {
    name: "京仓",
    id: '京仓',
  },
  {
    name: "第三方",
    id: '第三方',
  },
]);

const canarrives = ref([
  {
    name: "全部",
    id: '0',
  },
  {
    name: "已上架",
    id: 'Y',
  },
  {
    name: "未上架",
    id: 'N',
  },
]);

const pageParams = ref({
  categories: [0],
  sendtypes: '0',
  canarrives: '0',
  page: 1,
  template: 0,
  keyword: "",
  size: 10,
});
const total = ref(0)

const pagination = computed(() => ({
  total: total.value,
  current: pageParams.value.page,
  pageSize: pageParams.value.size,
}));

onMounted(() => {
  getList()
})

const getList = () => {
  tabLoading.value = true
  let params = _.cloneDeep(pageParams.value)
  params.categories = params.categories.join(',')
  params.categories.includes(0) && delete params.categories
  params.sendtypes.includes(0) && delete params.sendtypes
  params.canarrives.includes(0) && delete params.canarrives
  api.getProductList(params).then(res => {
    pool_list.value = res.data.list
    total.value = res.data.total
    tabLoading.value = false
  }).catch(() => {
    tabLoading.value = false
  })
}

const changeSelect = (key, val) => {
  pageParams.value[key] = val + '';
  pageParams.value.page = 1;
  getList()
};

const changeCategories = (val) => {
  let arr = pageParams.value.categories
  if (val == 0) {
    arr = [0]
  } else {
    if (arr.includes(val)) {
      arr = arr.filter(item => item !== val);
    } else {
      arr.push(val);
    }
    if (arr.length > 0 && arr.includes(0)) {
      arr = arr.filter(item => item !== 0);
    } else if (arr.length == 0 && !arr.includes(0)) {
      arr.push(0);
    }
  }
  pageParams.value.categories = arr
  pageParams.value.page = 1;
  getList()
}

const handleTableChange = (e) => {
  pageParams.value.page = e.current
  getList()
};

const onSearch = () => {
  pageParams.value.page = 1;
  getList()
};

const checkArrive = () => {
  api.checkArrive({
    canarrives: pageParams.value.canarrives.includes('0') ? '' : pageParams.value.canarrives,
    categories: pageParams.value.categories.includes(0) ? '' : pageParams.value.categories.join(','),
    sendtypes: pageParams.value.sendtypes.includes('0') ? '' : pageParams.value.sendtypes,
    keyword: pageParams.value.keyword,
  }).then(res => {
    message.success('商品上架成功！')
  })
}
</script>

<template>
  <div>
    <div class="select-header">
      <a-flex wrap="wrap" gap="small" align="center">
        <span>商品类目：</span>
        <a-button class="min-w-70px" v-for="item of category_list"
          :type="pageParams.categories.includes(item.cid) ? 'primary' : 'default'" :key="item.cid"
          @click="changeCategories(item.cid)">{{ item.name }}</a-button>
      </a-flex>
      <a-flex wrap="wrap" gap="small" align="center" class="mt-16px">
        <span>发货方式：</span>
        <a-button class="min-w-70px" v-for="item of sendtypes"
          :type="pageParams.sendtypes == item.id ? 'primary' : 'default'" :key="item.id"
          @click="changeSelect('sendtypes', item.id)">{{ item.name }}</a-button>
      </a-flex>
      <a-flex wrap="wrap" gap="small" align="center" class="mt-16px">
        <span>商品状态：</span>
        <a-button class="min-w-70px" v-for="item of canarrives"
          :type="pageParams.canarrives == item.id ? 'primary' : 'default'" :key="item.id"
          @click="changeSelect('canarrives', item.id)">{{ item.name }}</a-button>
        <a-flex wrap="wrap" gap="small" align="center" class="ml-36px">
          <span>当前使用模板：</span>
          <a-select class="min-w-150px" v-model:value="selectTemplate" placeholder="请选择模板" :options="templateList">
          </a-select>
          <a-button type="link" @click="openTemplate = true">新增模板</a-button>
        </a-flex>
        <a-popconfirm title="是否上架该条件下全部商品？" ok-text="确认" cancel-text="取消" @confirm="checkArrive">
          <a-button type="primary" class="ml-auto">当前筛选条件下商品全部上架</a-button>
        </a-popconfirm>
        <span class="ml-16px">商品搜索：</span>
        <a-input-search class="w-260px" v-model:value="pageParams.keyword" placeholder="请输入商品关键词" enter-button
          @search="onSearch" />
      </a-flex>
    </div>

    <a-table class="mt-16px" :scroll="{ y: 'calc(100vh - 440px)' }" :columns="PRODUCT_POOL" :data-source="pool_list"
      :pagination="pagination" :loading="tabLoading" @change="handleTableChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'itemTitle'">
          <div class="flex ">
            <div class="w-80px h-80px">
              <img :src="record.picUrl" class="w-80px h-80px block" :fallback="defaultImg" />
            </div>
            <div class="ml-8px mr-30px">
              <div class=" font-18px line-clamp-2 overflow-hidden">{{ record.itemTitle }}</div>
              <div class="font-16px text-gray-500 whitespace-nowrap">
                {{ record.skuProperties }}
              </div>
            </div>
          </div>
        </template>
        <template v-if="column.key === 'skuPromotionPrice'">
          <a-statistic :valueStyle="{ 'font-size': '16px' }" :precision="2" prefix="￥"
            :value="record.skuPromotionPrice" />
        </template>
        <template v-if="column.key === 'skuOriginalPrice'">
          <a-statistic :valueStyle="{ 'font-size': '16px' }" :precision="2" prefix="￥"
            :value="record.skuOriginalPrice" />
        </template>
        <template v-if="column.key === 'profit'">
          <a-statistic :valueStyle="{ 'font-size': '16px' }" :precision="2" suffix="%"
            :value="`${(record.skuOriginalPrice - record.skuPromotionPrice) / record.skuOriginalPrice * 100}`" />
        </template>
        <template v-if="column.key === 'minimumPerOrder'">
          {{ record.minimumPerOrder || '-' }}
        </template>
        <template v-if="column.key === 'canSell'">
          <a-tag v-if="record.canSell === 'Y'" color="success">是</a-tag>
          <a-tag v-else color="error">否</a-tag>
        </template>
        <template v-if="column.key === 'operation'">
          <a-button type="link" @click="openPdDetail = true; pdId = record.skuId">更多信息</a-button>
        </template>
      </template>
    </a-table>
    <ProductInfo v-model:open="openTemplate"></ProductInfo>
    <ProductDetail v-model:open="openPdDetail" :id="pdId"></ProductDetail>
  </div>
</template>

<style>
.main-table {}
</style>